#include "bsp_rf433.h"

void rf433_handle_parsed_data(uint8_t *data)
{
    printf("rf433_handle_parsed_data: %02x %02x %02x\n", data[0], data[1], data[2]);
}

// 全局 RF433 上下文
static RF433_Context_t rf433_ctx = {
    .decode_state = STATE_LEAD_CODE,
    .lead_code_count = 0,
    .high_bit_count = 0,
    .low_bit_count = 0,
    .high_bit_duration = 0,
    .low_bit_duration = 0,
    .received_buffer = {0, 0, 0},
    .received_byte_count = 0,
    .bit_count = 0,
    .received_data = 0,
    .data_handler = rf433_handle_parsed_data,
};

// 注册数据处理回调函数
void bsp_rf433_register_handler(RF433_Data_Handler_t handler) { rf433_ctx.data_handler = handler; }

// 初始化 RF433 模块
void bsp_rf433_init(void)
{
    LL_GPIO_InitTypeDef gpio_initpara = {0};
    LL_TIM_InitTypeDef timer_initpara = {0};

    RF433_GPIO_CLK_ENABLE();
    gpio_initpara.Pin = RF433_PIN;
    gpio_initpara.Mode = LL_GPIO_MODE_INPUT;
    gpio_initpara.Pull = LL_GPIO_PULL_NO;
    gpio_initpara.Speed = LL_GPIO_SPEED_FREQ_HIGH;
    LL_GPIO_Init(RF433_PORT, &gpio_initpara);

    LL_TIM_DeInit(RF433_TIM_NBR);
    
    /* timer base configure */
    RF433_TIM_CLK_ENABLE();
    timer_initpara.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
    timer_initpara.CounterMode = LL_TIM_COUNTERMODE_UP;
    timer_initpara.Prescaler = (SystemCoreClock / 1000000) - 1;
    timer_initpara.Autoreload = TIME_CYCLE - 1;
    timer_initpara.RepetitionCounter = 0;
    LL_TIM_Init(RF433_TIM_NBR, &timer_initpara);
    LL_TIM_DisableARRPreload(RF433_TIM_NBR);

    LL_TIM_EnableIT_UPDATE(RF433_TIM_NBR);
    LL_TIM_EnableCounter(RF433_TIM_NBR);
        
    /* interrupt config */
    NVIC_EnableIRQ(RF433_TIM_IRQn);
    NVIC_SetPriority(RF433_TIM_IRQn, 0);
    
    /* start timer */
    LL_TIM_EnableCounter(RF433_TIM_NBR);
}

// 重置解码参数
static void reset_decode_params(void)
{
    rf433_ctx.bit_count = 0;
    rf433_ctx.received_data = 0x00;
    rf433_ctx.received_byte_count = 0;
    rf433_ctx.lead_code_count = 0;
    rf433_ctx.high_bit_count = 0;
    rf433_ctx.low_bit_count = 0;
    rf433_ctx.high_bit_duration = 0;
    rf433_ctx.low_bit_duration = 0;
    rf433_ctx.decode_state = STATE_LEAD_CODE;
}

// 解码数据位并存入缓冲区
static void process_data_bits(void)
{
    rf433_ctx.received_data <<= 1;
    if (rf433_ctx.high_bit_duration > rf433_ctx.low_bit_duration)
    {
        rf433_ctx.received_data |= 0x01; // 高电平长，解码为 1
    }
    else
    {
        rf433_ctx.received_data &= 0xFE; // 低电平长，解码为 0
    }

    rf433_ctx.bit_count++;
    if (rf433_ctx.bit_count == 8)
    {
        rf433_ctx.received_buffer[rf433_ctx.received_byte_count] = rf433_ctx.received_data;
        rf433_ctx.received_data = 0x00;
        rf433_ctx.bit_count = 0;
        rf433_ctx.received_byte_count++;
    }
}

// RF433 解码主逻辑
static void rf433_decode(void)
{
    switch (rf433_ctx.decode_state)
    {
    case STATE_LEAD_CODE:
        if (RFDI == 0)
        { // 低电平，计数引导码
            rf433_ctx.lead_code_count++;
        }
        else
        { // 高电平，检查引导码范围
            if (rf433_ctx.lead_code_count >= MIN_LEAD_CODE && rf433_ctx.lead_code_count <= MAX_LEAD_CODE)
            {
                rf433_ctx.lead_code_count = 0;
                reset_decode_params();
                rf433_ctx.decode_state = STATE_HIGH_BIT;
            }
            else
            {
                rf433_ctx.lead_code_count = 0;
            }
        }
        break;

    case STATE_HIGH_BIT:
        if (RFDI == 1)
        { // 高电平，计数
            rf433_ctx.high_bit_count++;
        }
        else
        { // 低电平，检查高电平范围
            if (rf433_ctx.high_bit_count >= MIN_BIT_DURATION && rf433_ctx.high_bit_count <= MAX_BIT_DURATION)
            {
                rf433_ctx.high_bit_duration = rf433_ctx.high_bit_count;
                rf433_ctx.high_bit_count = 0;
                rf433_ctx.decode_state = STATE_LOW_BIT;
            }
            else
            {
                reset_decode_params();
            }
        }
        break;

    case STATE_LOW_BIT:
        if (RFDI == 0)
        { // 低电平，计数
            rf433_ctx.low_bit_count++;
        }
        else
        { // 高电平，检查低电平范围
            if (rf433_ctx.low_bit_count >= MIN_BIT_DURATION && rf433_ctx.low_bit_count <= MAX_BIT_DURATION)
            {
                rf433_ctx.low_bit_duration = rf433_ctx.low_bit_count;
                rf433_ctx.low_bit_count = 0;
                rf433_ctx.decode_state = STATE_DATA_PROCESS;
            }
            else
            {
                reset_decode_params();
            }
        }
        break;

    case STATE_DATA_PROCESS:
        process_data_bits();
        if (rf433_ctx.received_byte_count == 3)
        {
            rf433_ctx.decode_state = STATE_PACKET_COMPLETE;
        }
        else
        {
            rf433_ctx.decode_state = STATE_HIGH_BIT;
        }
        break;

    case STATE_PACKET_COMPLETE:
        if (rf433_ctx.data_handler != NULL)
        {
            rf433_ctx.data_handler(rf433_ctx.received_buffer);
        }
        reset_decode_params();
        rf433_ctx.decode_state = STATE_LEAD_CODE;
        break;

    default:
        reset_decode_params();
        break;
    }
}

void RF433_TIM_IRQn_Handler(void)
{
    LL_TIM_ClearFlag_UPDATE(RF433_TIM_NBR);
    rf433_decode();
}
